package com.yc.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import com.yc.utils.YcUtils;
import com.yc.weixin.bean.Token;

/**
 * 微信通用工具类
 * 
 * @author zy
 * 
 */
public class WeiXinCommonUtil {

	/**
	 * 
	 * @author shuang
	 * @param requestUrl    :请求链接
	 * @param requestMethod 请求的方式GET或者HTTP
	 * @param outputStr
	 * @return
	 * @throws Exception
	 */
	public static JSONObject httpsRequest(String requestUrl,
			String requestMethod, String outputStr) throws Exception {
		JSONObject jsonObject = null;
		InputStream inputStream = null;
		InputStreamReader reader = null;
		BufferedReader bufferedReader = null;
		HttpsURLConnection con = null;
		try {
			//建立链接
			URL url = new URL(requestUrl);
			con = (HttpsURLConnection) url.openConnection();
			//使用自定义信任管理器
			TrustManager[] tms = { new YcX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tms, new SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			con.setSSLSocketFactory(ssf);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			//设置请求方式
			con.setRequestMethod(requestMethod);
			if (outputStr != null) {
				OutputStream outputStream = con.getOutputStream();
				outputStream.write(outputStr.getBytes("utf-8"));
			}
			//取得输入流
			inputStream = con.getInputStream();
			reader = new InputStreamReader(inputStream, "utf-8");
			bufferedReader = new BufferedReader(reader);
			//读取响应内容
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (Exception e) {
			YcUtils.error(e);
			throw e;
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
			if (con != null) {
				con.disconnect();
			}
		}

		return jsonObject;

	}
/**
 * @auther shuang
 * @param appid:用户注册账号时候拥有的参数
 * @param appsecret用户注册账号时候拥有的参数
 * @return
 */
	public static Token getToken(String appid, String appsecret) {
		Token token = null;
		String requestUrl = WeixinbasicKey.TOKEN_URL.replace("APPID", appid).replace(
				"APPSECRET", appsecret);
		JSONObject jsonObject = null;
		try {
			// 发起请求，获取凭证json格式
			jsonObject = httpsRequest(requestUrl, "GET", null);
			if (null != jsonObject) {
				token = new Token();
				token.setAccessToken(jsonObject.getString("access_token"));
				token.setExpiresIn(jsonObject.getInt("expires_in"));
			}
		} catch (Exception e) {
			YcUtils.error("获取tocke失败:" + jsonObject.getInt("errcode")
					+ "," + jsonObject.getString("errmsg"));

		}
		return token;
	}
	
	
	/**
	 * 判断传过来的文本是否是QQ表情
	 * @param content
	 * @return
	 */
	public static boolean isQqFace(String content) {
		boolean result = false;
		// 判断QQ表情的正则表达式
		String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
		Pattern p = Pattern.compile(qqfaceRegex);
		Matcher m = p.matcher(content);
		if (m.matches()) {
			result = true;
		}
		return result;
	}

}
